package view;

import dao.User;
import dao.UserDao;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.WebContext;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.SQLException;

@WebServlet("/login")
public class Login extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html; charset=utf-8");
//        ServletContext context = this.getServletContext();
//        TemplateEngine engine = (TemplateEngine) context.getAttribute("engine");
//        WebContext webContext = new WebContext(req,resp,context);
//        engine.process("login",webContext,resp.getWriter());
        resp.sendRedirect("login.html");
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8");
        String userName = req.getParameter("userName");
        String passWord = req.getParameter("passWord");
        if (userName == null || userName.equals("") || passWord == null || passWord.equals("")){
            String html = "<h3> 缺少登录字段 </h3>";
            resp.getWriter().write(html);
            return;
        }
        UserDao userDao = new UserDao();
        try {
            User user = userDao.selectName(userName);
            if (user == null){
                String html = "<h3> 用户名或密码不正确 </h3>";
                resp.getWriter().write(html);
                return;
            }
            if (!user.getPassWord().equals(passWord)){
                String html = "<h3> 用户名或密码不正确 </h3>";
                resp.getWriter().write(html);
                return;
            }
            HttpSession httpSession = req.getSession(true);
            httpSession.setAttribute("user",user);
            resp.sendRedirect("blogList.html");
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
